package com.enqualcomm.kids.activities;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.enqualcomm.kids.R;
import com.enqualcomm.kids.base.BaseActivity;
import com.enqualcomm.kids.config.userdefault.AppDefault;
import com.enqualcomm.kids.config.userdefault.TerminalDefault;
import com.enqualcomm.kids.config.userdefault.UserTerminalDefault;
import com.enqualcomm.kids.manager.Controller;
import com.enqualcomm.kids.mvp.NetworkModel;
import com.enqualcomm.kids.network.NetworkListener;
import com.enqualcomm.kids.network.SocketRequest;
import com.enqualcomm.kids.network.socket.request.BasicParams;
import com.enqualcomm.kids.network.socket.request.SaveAlarmParams;
import com.enqualcomm.kids.network.socket.request.UpdateAlarmParams;
import com.enqualcomm.kids.network.socket.response.BasicResult;
import com.enqualcomm.kids.network.socket.response.QueryAlarmResult;
import com.enqualcomm.kids.network.socket.response.QueryUserTerminalInfoResult;
import com.enqualcomm.kids.network.socket.response.TerminallistResult;
import com.enqualcomm.kids.view.AlarmWheelView;
import com.enqualcomm.kids.view.wheelview.NumericWheelAdapter;

import java.util.Locale;

import common.utils.DensityUtil;
import common.utils.MyFrontUtil;
import common.utils.PlatformUtil;
import common.utils.PromptUtil;
import common.utils.TimeUtil;

public class AlarmSettingActivity extends BaseActivity implements View.OnClickListener, CompoundButton.OnCheckedChangeListener {
    private TerminallistResult.Terminal terminal;
    private NetworkModel networkModel;
    private boolean needInit;
    private QueryAlarmResult.Data alarm;

    AlarmWheelView wheelView_changeMinute;
    AlarmWheelView wheelView_changeSecond;
    CheckBox checkbox_allweek;
    CheckBox checkbox_monday;
    CheckBox checkbox_tuesday;
    CheckBox checkbox_wednesday;
    CheckBox checkbox_thursday;
    CheckBox checkbox_firday;
    CheckBox checkbox_saturday;
    CheckBox checkbox_sunday;
    EditText alarm_name_et;
    private boolean oldManMode;
    private String alarmName;
    Controller mController;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_alarm_setting);

        terminal = getIntent().getParcelableExtra("terminal");
        alarm = getIntent().getParcelableExtra("alarm");
        networkModel = new NetworkModel();
        mController = Controller.getInstance();
        mController.resetTerminalConfig(new TerminalDefault(terminal.terminalid).getConfig());
        oldManMode = mController.isOldMainMode();
//        oldManMode = Controller.getInstance().isOldMainMode();
        needInit = true;
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (needInit) {
            needInit = false;
            initView();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        networkModel.onStop();
    }

    private void initView() {
        //初始化标题栏
        findViewById(R.id.title_bar_left_iv).setOnClickListener(this);
        //名字，头像
        QueryUserTerminalInfoResult.Data info = new UserTerminalDefault(terminal.userterminalid).getInfo();

//        String title = oldManMode?getString(R.string.alarm_settings_old):getString(R.string.alarm_settings);
        String title = getString(R.string.alarm_settings);
//        setupTitleIcon(info,terminal.terminalid,terminal.userterminalid, title);
        if ("ZH".equals(Locale.getDefault().getLanguage().toUpperCase(Locale.getDefault()))) {
            setupTitleIcon(info, terminal.terminalid, terminal.userterminalid, title);
            TextView title_bar_terminal_name_tv = (TextView) findViewById(R.id.title_bar_terminal_name_tv);
            MyFrontUtil.initTextViewText(this, title_bar_terminal_name_tv, info.name, getString(R.string.t_alarm_begin),
                    getString(R.string.t_alarm_end), 2, 2 + info.name.length());
        } else {
            setupTitleIcon(info, terminal.terminalid, terminal.userterminalid, "Back");
        }

//        alarmName = oldManMode?"提醒":"闹钟";
        alarmName = getString(R.string.alarm_name_1);

        alarm_name_et = (EditText) findViewById(R.id.alarm_name_et);
        if (!TextUtils.isEmpty(alarm.name)) {
            alarm_name_et.setText(alarm.name);
            alarm_name_et.setSelection(alarm.name.length());
        }

//        alarm_name_et.setHint(oldManMode?R.string.input_alarm_name_old:R.string.input_alarm_name);
        alarm_name_et.setHint(R.string.input_alarm_name);

        findViewById(R.id.save_btn).setOnClickListener(this);


        int textSize = DensityUtil.adjustFontSize(PlatformUtil.windowWidth(this));
        String[] timeArray = alarm.time.split(":");
        wheelView_changeMinute = (AlarmWheelView) findViewById(R.id.wheelView_changeMinute);
        wheelView_changeMinute.setAdapter(new NumericWheelAdapter(0, 23));
        wheelView_changeMinute.setCyclic(true);
        wheelView_changeMinute.setCurrentItem(Integer.parseInt(timeArray[0]));
        wheelView_changeMinute.setLabel(getString(R.string.hour));
        wheelView_changeMinute.setTextSizeAndItemCount(textSize, 5);

        wheelView_changeSecond = (AlarmWheelView) findViewById(R.id.wheelView_changeSecond);
        wheelView_changeSecond.setAdapter(new NumericWheelAdapter(0, 59));
        wheelView_changeSecond.setCyclic(true);
        wheelView_changeSecond.setLabel(getString(R.string.minute));
        wheelView_changeSecond.setCurrentItem(Integer.parseInt(timeArray[1]));
        wheelView_changeSecond.setTextSizeAndItemCount(textSize, 5);

        checkbox_allweek = (CheckBox) findViewById(R.id.checkbox_allweek);
        checkbox_monday = (CheckBox) findViewById(R.id.checkbox_monday);
        checkbox_tuesday = (CheckBox) findViewById(R.id.checkbox_tuesday);
        checkbox_wednesday = (CheckBox) findViewById(R.id.checkbox_wednesday);
        checkbox_thursday = (CheckBox) findViewById(R.id.checkbox_thursday);
        checkbox_firday = (CheckBox) findViewById(R.id.checkbox_firday);
        checkbox_saturday = (CheckBox) findViewById(R.id.checkbox_saturday);
        checkbox_sunday = (CheckBox) findViewById(R.id.checkbox_sunday);


        if (alarm.week == 127) {
            checkbox_allweek.setChecked(true);
        }
        char[] weeknum = new char[7];
        String binaryString = Integer.toBinaryString(alarm.week);
//		System.out.println("binaryString: "+binaryString);"111110"
        for (int i = 0; i < binaryString.length(); i++) {
            weeknum[i] = binaryString.charAt(binaryString.length() - 1 - i);
        }

        if (weeknum[0] == '1') {
            checkbox_sunday.setChecked(true);
        }
        if (weeknum[1] == '1') {
            checkbox_monday.setChecked(true);
        }
        if (weeknum[2] == '1') {
            checkbox_tuesday.setChecked(true);
        }
        if (weeknum[3] == '1') {
            checkbox_wednesday.setChecked(true);
        }
        if (weeknum[4] == '1') {
            checkbox_thursday.setChecked(true);
        }
        if (weeknum[5] == '1') {
            checkbox_firday.setChecked(true);
        }
        if (weeknum[6] == '1') {
            checkbox_saturday.setChecked(true);
        }

        checkbox_allweek.setOnCheckedChangeListener(this);
        checkbox_monday.setOnCheckedChangeListener(this);
        checkbox_tuesday.setOnCheckedChangeListener(this);
        checkbox_wednesday.setOnCheckedChangeListener(this);
        checkbox_thursday.setOnCheckedChangeListener(this);
        checkbox_firday.setOnCheckedChangeListener(this);
        checkbox_saturday.setOnCheckedChangeListener(this);
        checkbox_sunday.setOnCheckedChangeListener(this);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.title_bar_left_iv:
                finish();
                break;
            case R.id.save_btn:
                //保存按钮
                alarm.name = alarm_name_et.getText().toString().trim();
                if ("".equals(alarm.name)) {
                    alarm.name = alarmName;//默认名称：闹钟
                }

                int hours = wheelView_changeMinute.getCurrentItem();
                int minute = wheelView_changeSecond.getCurrentItem();
                String strhours;
                String strminute;
                if (hours < 10) {
                    strhours = "0" + hours;
                } else {
                    strhours = "" + hours;
                }
                if (minute < 10) {
                    strminute = "0" + minute;
                } else {
                    strminute = "" + minute;
                }
                alarm.time = strhours + ":" + strminute;
                if (alarm.week == 0) {
                    alarm.week = TimeUtil.getNextDayOfWeek();
                }

                AppDefault appDefault = new AppDefault();
                String userid = appDefault.getUserid();
                String userkey = appDefault.getUserkey();
                if (alarm.alarmid == null) {//新增
                    SaveAlarmParams saveAlarmParams = new SaveAlarmParams(userkey, userid, terminal.terminalid,
                            alarm.time, 1, alarm.ringid, alarm.week, alarm.name);
                    send(saveAlarmParams);
                } else {//修改
                    UpdateAlarmParams updateAlarmParams = new UpdateAlarmParams(userkey, userid, terminal.terminalid, alarm.alarmid, alarm.time,
                            alarm.isopen, alarm.ringid, alarm.week, alarm.name);
                    send(updateAlarmParams);
                }
                break;
        }
    }

    public void send(BasicParams params) {
        showProgress();
        networkModel.loadDataFromServer(new SocketRequest<BasicResult>(params, new NetworkListener<BasicResult>() {
            @Override
            public void onError(VolleyError error) {
                hideProgress();
                PromptUtil.toast(getApplicationContext(), R.string.app_no_connection);
            }

            @Override
            public void onSuccess(BasicResult response) {
                hideProgress();
                if (response.code == 0) {
                    setResult(99);
                    finish();
                }
            }
        }));
    }

    private void setAllWeekState() {
        checkbox_allweek.setOnCheckedChangeListener(null);
        if (alarm.week == 127) {
            checkbox_allweek.setChecked(true);
        } else {
            checkbox_allweek.setChecked(false);
        }
        checkbox_allweek.setOnCheckedChangeListener(this);
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        switch (buttonView.getId()) {
            case R.id.checkbox_allweek:
                checkbox_monday.setChecked(isChecked);
                checkbox_tuesday.setChecked(isChecked);
                checkbox_wednesday.setChecked(isChecked);
                checkbox_thursday.setChecked(isChecked);
                checkbox_firday.setChecked(isChecked);
                checkbox_saturday.setChecked(isChecked);
                checkbox_sunday.setChecked(isChecked);
                break;
            case R.id.checkbox_monday:
                if (!isChecked) {
                    alarm.week -= 2;
                } else {
                    alarm.week += 2;
                }
                setAllWeekState();
                break;
            case R.id.checkbox_tuesday:
                if (!isChecked) {
                    alarm.week -= 4;
                } else {
                    alarm.week += 4;
                }
                setAllWeekState();
                break;
            case R.id.checkbox_wednesday:
                if (!isChecked) {
                    alarm.week -= 8;
                } else {
                    alarm.week += 8;
                }
                setAllWeekState();
                break;
            case R.id.checkbox_thursday:
                if (!isChecked) {
                    alarm.week -= 16;
                } else {
                    alarm.week += 16;
                }
                setAllWeekState();
                break;
            case R.id.checkbox_firday:
                if (!isChecked) {
                    alarm.week -= 32;
                } else {
                    alarm.week += 32;
                }
                setAllWeekState();
                break;
            case R.id.checkbox_saturday:
                if (!isChecked) {
                    alarm.week -= 64;
                } else {
                    alarm.week += 64;
                }
                setAllWeekState();
                break;
            case R.id.checkbox_sunday:
                if (!isChecked) {
                    alarm.week -= 1;
                } else {
                    alarm.week += 1;
                }
                setAllWeekState();
                break;

            default:
                break;
        }
    }

}
